/*
 * GoodsCountMenu.java
 * business
 *
 * Created by ChenTao on 2017/2/21.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.widget.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.yidiandao.business.R;
import com.yidiandao.business.ui.widget.dialog.ChangeGoodsCountDialog;
import com.yidiandao.business.utils.UIUtils;

/**
 * 商品数量编辑菜单
 */
public class GoodsCountMenu extends LinearLayout
        implements View.OnClickListener,
        TextWatcher,
        View.OnFocusChangeListener,
        View.OnTouchListener,
        ChangeGoodsCountDialog.OnConfirmDialogGoodsCountListener {

    /**
     * 可以编辑EditText，点击编辑EditText，修改数量
     */
    public static final int MODE_EDIT = 0;

    /**
     * 不可以编辑EditText，点击EditText弹出修改商品数量对话框。在对话框中修改商品数量。
     */
    public static final int MODE_CLICK_SHOW_DIALOG = 1;

    private ImageView mTvSubtract;

    private EditText mEtCount;

    private ImageView mTvAdd;

    private OnGoodsCountChangeListener mListener;

    private String mNoMoreCountHintText = UIUtils.getString(R.string.no_nore_goods);

    private int mGoodsCount;

    private int mMaxGoodsCount = Integer.MAX_VALUE;

    private int mMinGoodsCount = 1;

    private int mCurrentMode;

    private boolean mEditTextHasFocus;

    private ChangeGoodsCountDialog mChangeGoodsCountDialog;

    private String mDialogOverStockTip;

    private String mChangeGoodsCountDialogTitle;

    public GoodsCountMenu(Context context) {
        this(context, null);
    }

    public GoodsCountMenu(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.GoodsCountMenu);
        mCurrentMode = typedArray.getInt(R.styleable.GoodsCountMenu_mode, MODE_CLICK_SHOW_DIALOG);
        typedArray.recycle();

        View root = LayoutInflater.from(context).inflate(R.layout.goods_count_menu, this);

        mTvSubtract = (ImageView) root.findViewById(R.id.tv_subtract);
        mEtCount = (EditText) root.findViewById(R.id.et_count);
        mTvAdd = (ImageView) root.findViewById(R.id.tv_add);

        mTvSubtract.setOnClickListener(this);
        mTvAdd.setOnClickListener(this);

        // 默认编辑模式，有加减号，先设置
        setMenuMode(mCurrentMode);
        // 默认商品数量
        setGoodsCount(mMinGoodsCount);
    }

    public void setNoMoreDataHintText(String hintText) {
        mNoMoreCountHintText = hintText;
    }

    private String getEditTextContent() {
        return mEtCount.getText().toString().trim();
    }

    /**
     * 设置当前数量编辑菜单的模式
     *
     * @param mode {@link #MODE_EDIT} {@link #MODE_CLICK_SHOW_DIALOG}
     */
    public void setMenuMode(int mode) {
        mCurrentMode = mode;

        if (mode != MODE_EDIT) {
            mEtCount.setKeyListener(null);
        } else {
            mEtCount.setOnFocusChangeListener(this);
        }

        mEtCount.setCursorVisible((mode == MODE_EDIT));

        // 是否添加click监听
        mEtCount.setOnTouchListener((mode == MODE_CLICK_SHOW_DIALOG) ? this : null);
    }

    public void setSubtractButtonEnable(boolean enable) {
        mTvSubtract.setEnabled(enable);
    }

    /**
     * 设置最大的商品数量.
     * <p>
     * <p>该方法优先于{@link #setGoodsCount(int)}方法调用
     */
    public void setMaxGoodsCount(int maxGoodsCount) {
        mMaxGoodsCount = maxGoodsCount;
    }

    /**
     * 设置最小的商品数量.默认是1
     */
    public void setMinGoodsCount(int minGoodsCount) {
        mMinGoodsCount = minGoodsCount < 1 ? 1 : minGoodsCount;
    }

    public int getGoodsCount() {
        return mGoodsCount;
    }

    public int getMinGoodsCount() {
        return mMinGoodsCount;
    }

    /**
     * 设置商品数量，该方法仅在{@link #setMaxGoodsCount(int)}方法调用之后调用
     *
     * @param count 商品数量
     */
    public void setGoodsCount(int count) {
        if (count > mMaxGoodsCount) {
            showToast();
            mGoodsCount = mMaxGoodsCount;
            return;
        }

        if (count < 1) {
            count = 1;
            setSubtractButtonEnable(false);
        } else {
            setSubtractButtonEnable(true);
        }

        mGoodsCount = count;

        // 编辑模式与非编辑模式显示的文字不同
        mEtCount.setText(mGoodsCount + "");
        mEtCount.setSelection(getEditTextContent().length());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_subtract:
                setGoodsCount(--mGoodsCount);
                notifyGoodsCountChanged();
                break;
            case R.id.tv_add:
                setGoodsCount(++mGoodsCount);
                notifyGoodsCountChanged();
                break;
        }
    }

    public void setOnGoodsCountChangeListener(OnGoodsCountChangeListener listener) {
        mListener = listener;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {

        if (!mEditTextHasFocus) {
            return;
        }

        // 注意递归
        String text = s.toString();

        if (!TextUtils.isEmpty(text)) {
            int inputNumber = Integer.parseInt(text);
            if (inputNumber != 0) {
                // 内容不为空 且 输入的不是0
                mGoodsCount = inputNumber;
                // 设置减号可用/不可用
                setSubtractButtonEnable(mGoodsCount > 1);
            } else {
                // 输入内容为0时，设置为1
                setGoodsCount(1);
            }
        } else {
            // 没有输入具体数字时，设置为1
            mGoodsCount = 1;
        }

        if (mGoodsCount > mMaxGoodsCount) {
            // 超过最大值时，需要将显示设置为最大值
            setGoodsCount(mMaxGoodsCount);
            showToast();
        }
        notifyGoodsCountChanged();
    }

    private void showToast() {
        if (TextUtils.isEmpty(mDialogOverStockTip)) {
            UIUtils.showToast(UIUtils.getString(R.string.goods_stock_not_enough_now, mMaxGoodsCount));
        } else {
            UIUtils.showToast(mDialogOverStockTip);
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        mEditTextHasFocus = hasFocus;
        if (hasFocus) {
            // EditText获取到焦点时，添加监听
            mEtCount.addTextChangedListener(this);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 修改数量对话框
                if (mChangeGoodsCountDialog == null) {
                    mChangeGoodsCountDialog = new ChangeGoodsCountDialog(getContext());
                }
                mChangeGoodsCountDialog.show();
                mChangeGoodsCountDialog.initGoodsCount(getGoodsCount(), mMaxGoodsCount, mMinGoodsCount);
                mChangeGoodsCountDialog.setOverStockTipHint(mDialogOverStockTip);
                mChangeGoodsCountDialog.setDialogTitle(mChangeGoodsCountDialogTitle);
                mChangeGoodsCountDialog.setOnConfirmDialogGoodsCountListener(this);
                break;
        }

        return false;
    }

    /**
     * 设置超过最大值时的提示
     */
    public void setDialogOverStockTip(String dialogOverStockTip) {
        mDialogOverStockTip = dialogOverStockTip;
    }

    /**
     * 设置修改商品数量Dialog的Title
     */
    public void setChangeGoodsDialogTitle(String title) {
        mChangeGoodsCountDialogTitle = title;
    }

    /**
     * 触发回掉
     */
    private void notifyGoodsCountChanged() {
        if (mListener != null) {
            mListener.onGoodsCountChanged(getGoodsCount());
        }
    }

    @Override
    public void onConfirmDialogCount(int dialogGoodsCount) {
        // 将对话框中的商品数量设置给GoodsCountMenu
        setGoodsCount(dialogGoodsCount);
        // 触发数量的回掉
        notifyGoodsCountChanged();
    }

    /**
     * 商品数量变化的Listener
     */
    public interface OnGoodsCountChangeListener {

        /**
         * 商品数量发生变化时的回掉
         *
         * @param count 商品的数量
         */
        void onGoodsCountChanged(int count);
    }
}
